package org.example;

public class MyBlockQueue {
    //数组存放元素；
    private String[] elems = null;
    //头节点；
    private volatile int head = 0;
    //尾节点；
    private volatile int tail = 0;
    //队列内有效元素个数；
    private volatile int size = 0;
    //参数为数组容量的构造方法；
    public  MyBlockQueue(int capacity){
        elems = new String[capacity];
    }

    //入队列方法；
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while (size == elems.length){
                this.wait();
            }
            elems[tail] = elem;
            tail++;
            if(tail >= elems.length){
                tail = 0;
            }
            size++;
            this.notifyAll();
        }
    }
    //出队列方法；
    public String take() throws InterruptedException {
        String elem = null;
        synchronized (this){
            while (size == 0){
                this.wait();
            }
            elem = elems[head];
            elems[head] = null;
            head++;
            if(head >= elems.length){
                head = 0;
            }
            size--;
            this.notify();
        }
        return elem;
    }
}
